﻿using HuaskyWebAPI.Common;
using HuaskyWebAPI.Core.Exceptions;
using System.Security.Claims;

namespace HuaskyWebAPI.Core.Session;

public class SessionData
{
	private TokenData _token;

	/// <summary>
	/// 用户Id，如果不可用则抛异常
	/// </summary>
	public Guid StaffId
    {
        get
        {
			AssertEx.IsNotNull(_token.StaffId, "StaffId");
			return _token.StaffId;
		}
    }

    /// <summary>
    /// 用户姓名
    /// </summary>
    public string StaffName
    {
        get
        {
            AssertEx.IsNotNull(_token.StaffName, "StaffName");
            return _token.StaffName;
        }
    }

    /// <summary>
    /// 身份标识，如jwt的appId
    /// </summary>
    public Claim[] Claims { get; init; }

	public AuthState State { get;  }

	private SessionData(TokenData token, AuthState state)
	{
        _token = token;
		this.State = state;
    }


    /// <summary>
    /// 正常会话
    /// 有效会话staffId也可能为null （JWT对服务端认证的场景）
    /// </summary>
    public static SessionData Normal(TokenData token, Claim[] claims = null)
	{
		return new SessionData(token, AuthState.Normal)
		{
			Claims = claims,
		};
	}


	/// <summary>
	/// 获取用户Id，为null的时候不抛异常
	/// </summary>
	public Guid? GetStaffId() => _token.StaffId;

	#region 无效会话

	/// <summary>
	/// 过期会话
	/// </summary>
	public static SessionData Expired { get; } = new(null, AuthState.Expired);

	/// <summary>
	/// 未登录
	/// </summary>
	public static SessionData NotLogin { get; } = new(null, AuthState.NotLogin);

    #endregion


}

public record TokenData(Guid StaffId, string StaffName, string Source)
{
    public static TokenData Parse(string value)
    {
        return TokenHelper.ParseTokenString<TokenData>(value);
    }

    public string ToTokenString()
    {
        return TokenHelper.ToTokenString(this);
    }
}